package logic

import (
	"context"
	"errors"
	"shop-hub/models/cache"
	"shop-hub/models/mysql"

	"shop-hub/shoprpc/internal/svc"
	"shop-hub/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, errors.New("当前账号不存在")
	}
	if user.Password != in.Password {
		return nil, errors.New("密码错误重新输入")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()

	if in.CaptchaCode != result {
		return nil, errors.New("验证码错误请重新输入")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SmsCode != s {
		return nil, errors.New("短信验证码错误请重新输入")
	}

	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
